package org.wzh.three.mybatis.typealiases;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author ewanhiz
 */
public class Main {

    public static void main(String[] args) {
        SqlSession sqlSession = null;
        try {
            /**
             * intellij  不会编译src的java目录的xml文件　　
             * 所以需要将IDEA maven项目中src源代码下的xml等资源文件编译进classes文件夹,
             * 具体操作方法就是：配置maven的pom文件配置，在<build>节点下添加<resources>代码.
             */
            String resource = "org/wzh/three/mybatis/typealiases/configuration.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            /**
             * 方法一
             */
            sqlSession = sqlSessionFactory.openSession();
            Student student = sqlSession.selectOne("org.wzh.three.mybatis.typealiases.StudentDao.selectById", 1);
            System.out.println(student);

            Teacher teacher = sqlSession.selectOne("org.wzh.three.mybatis.typealiases.TeacherDao.selectById", 1);
            System.out.println(teacher);

            /**
             * 方法二
             * 不基于字符串常量，更安全
             */
            StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
            Student student2 = studentDao.selectById(2);
            System.out.println(student2);

            TeacherDao teacherDao = sqlSession.getMapper(TeacherDao.class);
            Teacher teacher2 = teacherDao.selectById(2);
            System.out.println(teacher2);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}
